<?php
namespace app\controller\admin\module;

use think\facade\View;
use think\response\Json;

class AdminBaseController extends BaseController
{
    protected array $admin;
    protected \app\model\BaseModel $model;
    protected string $modelName;

    protected function initialize()
    {
        $this->admin = $this->getLoginData();

        !empty($this->modelName) and $this->model = Model($this->modelName);

        View::assign('admin', $this->admin);
    }

    private function checkLogin(){
        $data = getCaches(session('token'), []);
        if(!checkCacheKey(session('token')) or empty($data)){
            return loginFailure();  //登出
        }
        return $data;
    }

    /**
     * 获取登录数据
     * @return Json|array
     */
    private function getLoginData()
    {
        $data = $this->checkLogin();
        $this->setLoginData(session('token'), $data);
        return $data;
    }

    /**
     * 更新登录数据
     * @param int $id
     * @param string $field
     * @return void
     */
    protected function updateLoginData(int $id, string $field){
        $info = Model('admin')->getInfo(['id' => $id], $field);
        !empty($info) and $this->setLoginData(session('token'), array_merge($this->checkLogin(), is_array($info) ? $info : [$field => $info]));
    }

}